//
// Created by lsj on 2015/12/31.
//
#include <stdio.h>
#include <assert.h>
#include <jni.h>
#include <string>
#include<stdlib.h>
extern "C" void __gcov_flush();

inline std::string jGetCString(JNIEnv* env, jstring str) {
    std::string s;
    if (str != NULL) {
        const char* utf = env->GetStringUTFChars(str, NULL);
        if (utf != NULL) {
            s = utf;
            env->ReleaseStringUTFChars(str, utf);
        }
    }

    return s;
}

jstring jGetJString(JNIEnv* env, const char* pstr){
	return env->NewStringUTF(pstr);
}

static jstring getString1(JNIEnv*  env, jobject thiz, jstring str){
	std::string ins  = jGetCString(env,  str);
	int i = 0;
	i++;
	char buff[128] = {0};
	sprintf(buff, "%s_%d", ins.c_str(), i);
    return jGetJString(env, buff);
}

static jstring getString2(JNIEnv*  env, jobject thiz, jstring str){
	std::string ins  = jGetCString(env, str);
	int i = 0;
	i++;
	i++;
	char buff[128] = {0};
	sprintf(buff, "%s_%d", ins.c_str(), i);
    return jGetJString(env, buff);
}

static void init_native(JNIEnv*  env, jobject thiz, jstring out_path){
	std::string ins  = jGetCString(env, out_path);
	setenv("GCOV_PREFIX", ins.c_str(), 1);
	setenv("GCOV_PREFIX_STRIP", "1", 1); // 14是我要去掉的目录级别，不要的话就不设置这个变量
}

static void flush_cov(JNIEnv*  env, jobject thiz){
	__gcov_flush();
}


const char* const kClassPathName = "com/kugou/test/helper/JniCoverage";
static JNINativeMethod gMethods[] = {
	    {"init_native",				   "(Ljava/lang/String;)V",					(jstring *)init_native},
		{"flush_cov",				   "()V",									(jstring *)flush_cov},
/*        {"getString1",                 "(Ljava/lang/String;)Ljava/lang/String;",                   (jstring *)getString1},
		{"getString2",                 "(Ljava/lang/String;)Ljava/lang/String;",                   (jstring *)getString2},
		{"gcovFlush",                 "()V",                                                     (void *)gcovFlush},*/
};

jint JNI_OnLoad( JavaVM* vm, void* reserved )
{	
    JNIEnv* env = NULL;
    jclass clazz;
    jint result = -1;

    if( vm->GetEnv( ( void** )&env, JNI_VERSION_1_4 ) != JNI_OK )
    {
        return result;
    }
    assert( env != NULL );

    clazz = env->FindClass( kClassPathName );
    if( clazz == NULL )
    {
        return result;
    }
    if( env->RegisterNatives( clazz, gMethods, sizeof( gMethods ) / sizeof( gMethods[ 0 ] ) ) < 0 )
    {
        return result;
    }

    /* success -- return valid version number */
    result = JNI_VERSION_1_4;
    return result;
}